package group.rober.base.aspect;

import group.rober.base.autoconfigure.BaseProperties;
import group.rober.runtime.kit.BeanKit;
import group.rober.runtime.kit.DateKit;
import group.rober.runtime.lang.MapData;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;

/**
 * rober-sql模块，作数据插入时，记录数据的创建时间，更新时间
 */

@Aspect
@Component
public class MapDataUpdaterWhenDidAspect {
    @Autowired
    protected BaseProperties properties;

    @Pointcut("execution(* group.rober.sql.core.MapDataUpdater.insert(..))")
    public void insertPointCut() {
    }
    @Pointcut("execution(* group.rober.sql.core.MapDataUpdater.update(..))")
    public void updatePointCut() {
    }

    protected void fillProperty(Object object,String propName,Object value){
        if(object instanceof Iterable){
            fillBeans((Iterable)object,propName,value);    //列表集合类的处理
        }else{
            touchBeanValue(object,propName,value);
        }
    }

    protected void fillBeans(Iterable<?> iterable,String propName,Object value){
        Iterator<?> iterator = iterable.iterator();
        while(iterator.hasNext()){
            touchBeanValue(iterator.next(),propName,value);
        }
    }

    private void touchBeanValue(Object object,String name,Object value){
        if(object instanceof MapData){
            ((MapData)object).put(name,value);
        }
    }

    @Before("insertPointCut()")
    public void doInsertBefore(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        if(args==null||args.length<2)return;
        Object object = args[1];

        fillProperty(object,properties.getCreatedTimePropertyName(),DateKit.now());
        fillProperty(object,properties.getUpdatedTimePropertyName(),DateKit.now());
    }



    @Before("updatePointCut()")
    public void doUpdateBefore(JoinPoint joinPoint){
        Object[] args = joinPoint.getArgs();
        if(args==null||args.length<2)return;
        Object object = args[1];
        //在更新模式下，如果更新日期为空，也给它填上去
        Object v = BeanKit.getPropertyValue(object,properties.getCreatedTimePropertyName());
        if(v==null){
            fillProperty(object,properties.getCreatedTimePropertyName(),DateKit.now());
        }
        fillProperty(object,properties.getUpdatedTimePropertyName(),DateKit.now());

    }


}
